import numpy as np
import pandas as pd
import sklearn
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import os

# 中值平均值滤波
def MedianAvg_Filter(window_left, window_right, arr):
  size = len(arr)
  result = []
  for i in range(window_left, size-window_right):
    # 滑窗
    temp = []
    for j in range(-window_left, window_right+1):
      temp.append(arr[i+j])
    temp.sort()
    # 可以去掉最大值后，取中位数的平均值
    median_mean = []
    for m in range(1, len(temp)-1):
      median_mean.append(temp[m])

    result.append(np.mean(median_mean))
  return result

'''
对外调用接口;
提供给外部其他Python文件调用接口.
'''
def data_process(data,url):
    if url:
        df = pd.read_excel(url)
    else:
        df = data
    df.columns = ['y']
    # 滤波后的数据
    data1 = df[:1000]
    data_filter = np.array(MedianAvg_Filter(10, 10, data1['y'])).reshape(-1, 1)

    # 用前1000轮预测后100轮
    train = pd.DataFrame(data_filter)
    test = df[-100:]
    poly = PolynomialFeatures(degree=2)
    x1 = np.arange(0, len(train)).reshape(-1, 1)
    poly.fit(x1)
    y1 = train.values
    x2 = poly.transform(x1)
    lin_reg2 = LinearRegression()
    lin_reg2.fit(x2, y1)
    y_predict2 = lin_reg2.predict(x2).tolist()
    x3 = np.arange(len(train), len(train)+len(test)).reshape(-1, 1)
    poly.fit(x3)
    x4 = poly.transform(x3)
    y_predict4 = lin_reg2.predict(x4).tolist()
    return y_predict2, y_predict4

if __name__ =="__main__":
    # 读取文件
    url = 'Poly_data.xlsx'
    data = pd.read_excel('Poly_data.xlsx')
    _, test_predict = data_process(data,url)

    # 输出预测值
    print('Predict:', test_predict)
